# coding=utf-8

import os, time, psutil
from subprocess import PIPE
import mysql.connector


mysql_host = os.getenv('MYSQL_HOST', '127.0.0.1')
mysql_port = os.getenv('MYSQL_PORT', 3306)
mysql_user = os.getenv('MYSQL_USER', 'root')
mysql_password = os.getenv('MYSQL_PASSWORD', 'root')

cluster_node_ip = os.getenv('CLUSTER_NODE_IP')

def init_db():
    proc = psutil.Popen(["cloudstack-setup-databases", "cloud:password@{}:{}".format(mysql_host, mysql_port),
        "--deploy-as={}:{}".format(mysql_user, mysql_password), '-i {}'.format(cluster_node_ip)], stdout=PIPE)

    while True:
        proc.poll()
        out = proc.stdout.readline()
        if out == '':
            break
        yield out

# check mysql is enable for cloudstack
print('# Checking the mysql connecting info:')
while True:
    try:
        need_init_db = False
        connector = mysql.connector.connect(user=mysql_user,password=mysql_password, host=mysql_host, database='mysql')
        cur = connector.cursor()
        cur.execute('show databases')
        tables = map(lambda x: x[0], cur.fetchall())
        if 'cloud' not in tables:
            print("wating a while, i am creating db for you")
            for i in init_db():
                print(i)
        break
    except Exception as e:
        time.sleep(3)
        print('can not connect to mysql')
        print e